package com.ruyuan.seckilling.render.async.listener;

import com.alibaba.fastjson.JSON;
import com.ruyuan.seckilling.render.async.BaseRenderPageListener;
import com.ruyuan.seckilling.render.async.PageRenderContext;
import com.ruyuan.seckilling.render.async.event.Event03GetAggrData;
import com.ruyuan.starter.async.anno.Channel;
import com.ruyuan.starter.async.event.BaseEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

import static com.ruyuan.seckilling.common.ChannelKey.CHANNEL_03_AGGR_DATA;
import static com.ruyuan.seckilling.common.ChannelKey.CHANNEL_04_RENDER_PAGE;
import static com.ruyuan.seckilling.render.async.PageRenderEventHolder.EVENT_04;

/**
 * @author zhonghuashishan
 */
@Slf4j
@Component
@Channel(CHANNEL_03_AGGR_DATA)
public class Event03Listener extends BaseRenderPageListener<Event03GetAggrData> {

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public boolean accept(BaseEvent event) {
        return event instanceof Event03GetAggrData;
    }

    /**
     * 3、调用dataUrl获取聚合数据
     */
    @Override
    protected void doThisStep(Event03GetAggrData event, PageRenderContext context) {

        Runnable task = () -> {
            String aggrDataUrl = context.getPageConfig().getAggrDataUrl();
            Map params = context.getParams();
            Map map = restTemplate.postForObject(aggrDataUrl, params, Map.class);
            if (MapUtils.isEmpty(map)) {
                context.getPageLog().setSuccess(false);
                context.getPageLog().setInfo("聚合数据有问题");
                context.setShouldSkip(true);
                return;
            }
            context.setAggrData(map);
            bossEventBus.publish(CHANNEL_04_RENDER_PAGE, EVENT_04, context);
            log.info("第3步，调用聚合数据的接口，aggrData={}", JSON.toJSONString(map, true));
        };

        executorService.execute(CHANNEL_03_AGGR_DATA, task);
    }
}
